package org.javaweb.cms_web.interceptor;


import org.javaweb.cms_web.model.User;
import org.javaweb.cms_web.util.HostHolder;
import org.javaweb.cms_web.model.Enum.RoleType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class RoleBasedAccessInterceptor implements HandlerInterceptor {

    private final HostHolder hostHolder;

    public RoleBasedAccessInterceptor(HostHolder hostHolder) {
        this.hostHolder = hostHolder;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取当前登录的用户
        User user = hostHolder.getUser();

        if (user == null) {
            response.sendRedirect("/login");  // 未登录，重定向到登录页
            return false;
        }

        // 获取请求的URI
        String uri = request.getRequestURI();

        // 获取用户角色类型
        Integer roleType = user.getRoleType();

        // 获取用户角色的路径前缀
        String rolePrefix = getRolePrefix(roleType);

        // 判断请求的URI是否以当前用户的角色路径开头
        if (uri.startsWith("/" + rolePrefix)) {
            return true;  // 允许访问
        } else {
            response.sendRedirect("/login.jsp");
            return false;
        }
    }

    private String getRolePrefix(Integer roleType) {
        // 根据角色类型返回对应的路径前缀
        switch (RoleType.values()[roleType]) {
            case SUPER_ADMIN:
                return "superAdmin";
            case TEAM_ADMIN:
                return "admin";
            case TEAM_MEMBER:
                return "team-member";
            case VISITOR:
                return "visitor";
            default:
                return "";
        }
    }
}